import React, { Component } from "react";
// antd
import {message,Radio,Button,Form,Input,InputNumber} from "antd";
// api
import {getDepartmentByID,addDepartment,updateDepartment} from '@api/department'
export default class Add extends Component {
    state={
        formLayout:{
            labelCol:{span:2},
            wrapperCol:{span:15}
        },
        defaultValue:true,
        loading:false
    }
    formRef=React.createRef()
    // 点击编辑按钮跳转过来的 编辑和新增共用一个页面
    // 没传 就没有state
    componentDidMount(){
        if(!this.props.location.state) return false
        getDepartmentByID(this.props.location.state.pid).then(res=>{
            console.log(res)
            this.formRef.current.setFieldsValue(res.data)
        })
    }

    onFinish=(value)=>{
        console.log(value);
        if(!value.departmentName){
            message.warning('部门名称不能为空')
            return false
        }
        if(!value.peopleNumber||value.peopleNumber === 0){
            message.warning('部门人数不能为空')
            return false
        }
        if(!value.description){
            message.warning('部门描述不能为空')
            return false
        }
        this.setState({loading:true})

        this.props.location.state?
        updateDepartment(value).then(response=>{
            message.success('添加成功')
        }).catch(err=>{
            message.error('添加失败')
        })
        :
        addDepartment(value).then(response=>{
            message.success('添加成功')
        }).catch(err=>{
            message.error('添加失败')
        })

        this.setState({loading:false})
        this.formRef.current.resetFields()
    }
    render(){
        return(
        <div  className="site-layout-background" style={{padding: 24, minHeight: 360}}>
            <Form onFinish={this.onFinish} {...this.state.formLayout} ref={this.formRef} initialValues={{status:false,number:1}}>
                <Form.Item label="部门名称" name='departmentName'>
                    <Input />
                </Form.Item>
                <Form.Item label="负责人" name='leader'>
                    <Input />
                </Form.Item>
                <Form.Item label="人员数量" name='peopleNumber'>
                    <InputNumber  min={0} max={100}/>
                </Form.Item>
                <Form.Item label="禁启用" name='status'>
                <Radio.Group >
                    <Radio value={1}>启用</Radio>
                    <Radio value={0}>禁用</Radio>
                </Radio.Group>
                </Form.Item>
                <Form.Item label="描述" name='description'>
                    <Input.TextArea />
                </Form.Item>
                <Form.Item>
                  <Button type='primary' htmlType='submit' loading={this.state.loading}>提交</Button>
                </Form.Item>
            </Form>
        </div>
        )
    }
   }

